/**
 * Copyright (c) 2008-2010 The Open Source Geospatial Foundation
 *
 * Published under the BSD license.
 * See http://svn.geoext.org/core/trunk/geoext/license.txt for the full text
 * of the license.
 */
/** api: example[toolbar]
 *  Toolbar with Actions
 *  --------------------
 *  Create a toolbar with GeoExt Actions.
 */


Ext.override(Ext.form.CheckboxGroup, {
  getNames: function() {
    var n = [];

    this.items.each(function(item) {
      if (item.getValue()) {
        n.push(item.getName());
      }
    });

    return n;
  },

  getValues: function() {
    var v = [];

    this.items.each(function(item) {
      if (item.getValue()) {
        v.push(item.getRawValue());
      }
    });

    return v;
  },

  setValues: function(v) {
    var r = new RegExp('(' + v.join('|') + ')');

    this.items.each(function(item) {
      item.setValue(r.test(item.getRawValue()));
    });
  }
});

Ext.override(Ext.form.RadioGroup, {
  getName: function() {
    return this.items.first().getName();
  },

  getValue: function() {
    var v;

    this.items.each(function(item) {
      v = item.getRawValue();
      return !item.getValue();
    });

    return v;
  },

  setValue: function(v) {
    this.items.each(function(item) {
      item.setValue(item.getRawValue() == v);
    });
  }
});


Ext.onReady(function(){
    Ext.QuickTips.init();
    
    map = new OpenLayers.Map();
    map.addControl(new OpenLayers.Control.LayerSwitcher());
    
    var gphy = new OpenLayers.Layer.Google("Google Physical", {
        type: google.maps.MapTypeId.TERRAIN
    });
    var gmap = new OpenLayers.Layer.Google("Google Streets", // the default
    {
        numZoomLevels: 20,
		streetViewControl: false
    });
    var ghyb = new OpenLayers.Layer.Google("Google Hybrid", {
        type: google.maps.MapTypeId.HYBRID,
        numZoomLevels: 20
    });
    var gsat = new OpenLayers.Layer.Google("Google Satellite", {
        type: google.maps.MapTypeId.SATELLITE,
        numZoomLevels: 22,
		streetViewControl: false
    });
    
    map.addLayers([ghyb, gphy, gmap, gsat]);
    
    
    var osm = new OpenLayers.Layer.OSM();
    
    map.addLayers([osm, gphy, gmap, ghyb, gsat]);
    
    
    
    
    
    //    var wms = new OpenLayers.Layer.WMS(
    //        "Global Imagery",
    //        "http://maps.opengeo.org/geowebcache/service/wms",
    //        {layers: "bluemarble"}
    //    );
    vector = new OpenLayers.Layer.Vector("vector");
    map.addLayers([vector]);
    
    var ctrl, toolbarItems = [], action, actions = {};
    
    //    // ZoomToMaxExtent control, a "button" control
    //    action = new GeoExt.Action({
    //        control: new OpenLayers.Control.ZoomToMaxExtent(),
    //        map: map,
    //        text: "max extent",
    //        tooltip: "zoom to max extent"
    //    });
    //    actions["max_extent"] = action;
    //    toolbarItems.push(action);
    //    toolbarItems.push("-");
    
    // Navigation control and DrawFeature controls
    // in the same toggle group
    action = new GeoExt.Action({
        text: "Pan",
		iconCls:'icon-pan',
        control: new OpenLayers.Control.Navigation(),
        map: map,
        // button options
        toggleGroup: "draw",
        allowDepress: false,
        pressed: true,
        tooltip: "navigate",
        // check item options
        group: "draw",
        checked: true
    });
    actions["nav"] = action;
    toolbarItems.push(action);
    
    action = new GeoExt.Action({
        text: "Draw Impact Area",
		iconCls: 'icon-draw-polygon',
        control: new OpenLayers.Control.DrawFeature(vector, OpenLayers.Handler.Polygon),
        map: map,
        // button options
        toggleGroup: "draw",
        allowDepress: false,
        tooltip: "draw polygon",
        // check item options
        group: "draw"
    });
    actions["drawpolygon"] = action;
    toolbarItems.push(action);
    
    action = new GeoExt.Action({
        text: "Edit",
		iconCls: 'icon-editfeature',
        control: new OpenLayers.Control.ModifyFeature(vector),
        map: map,
        // button options
        toggleGroup: "draw",
        allowDepress: false,
        tooltip: "Edit",
        // check item options
        group: "draw"
    });
    actions["edit"] = action;
    toolbarItems.push(action);
    //	action = new GeoExt.Action({
    //        text: "Draw Marker",
    //        control: new OpenLayers.Control.DrawFeature(
    //            vector, OpenLayers.Handler.Point
    //        ),
    //        map: map,
    //        // button options
    //        toggleGroup: "draw",
    //        allowDepress: false,
    //        tooltip: "Set Marker",
    //        // check item options
    //        group: "draw"
    //    });
    //    actions["drawmarker"] = action;
    
    //toolbarItems.push(action);
    // toolbarItems.push("-");
    
    // SelectFeature control, a "toggle" control
    action = new GeoExt.Action({
        text: "Select",
		iconCls: 'icon-select',
        control: new OpenLayers.Control.SelectFeature(vector, {
            type: OpenLayers.Control.TYPE_TOGGLE,
            hover: false
        }),
        map: map,
        // button options
        //enableToggle: true,
        gruop: 'draw',
        toggleGroup: "draw",
        tooltip: "select feature"
    });
    actions["select"] = action;
    toolbarItems.push(action);
    action = new GeoExt.Action({
        text: 'Set Marker',
		iconCls: 'icon-point',
        handler: function(){
            var i, fe;
            var fes = vector.features;
            var impacts = [];
            for (i = 0; i < fes.length; i++) {
            
                fe = fes[i];
                
                if (fe.geometry.CLASS_NAME == "OpenLayers.Geometry.Polygon") {
                    //it is an impact
                    var pt = new OpenLayers.Feature.Vector(fe.geometry.getCentroid());
                    pt.attributes['parent'] = fe.id;
                    
                    impacts.push(pt)
                    //pt.attributes['parent'] = fe.id;
                }
            }
            vector.addFeatures(impacts);
            
            
        }
        
    })
    toolbarItems.push(action);
    action = new GeoExt.Action({
        text: 'Delete',
		iconCls: 'icon-deletevector',
		
        handler: function(){
            var i, fe;
            var fes = vector.selectedFeatures;
            var impacts = [];
            for (i = 0; i < fes.length; i++) {
                fe = fes[i];
                fe.destroy();
            }
            
            
        }
        
    })
    toolbarItems.push(action);
    toolbarItems.push("-");
    
    // Navigation history - two "button" controls
    ctrl = new OpenLayers.Control.NavigationHistory();
    map.addControl(ctrl);
    
    action = new GeoExt.Action({
        text: "previous",
        control: ctrl.previous,
		iconCls: 'icon-zoom-previous',
        disabled: true,
        tooltip: "previous in history"
    });
    actions["previous"] = action;
    toolbarItems.push(action);
    
    action = new GeoExt.Action({
        text: "next",
        control: ctrl.next,
		iconCls: 'icon-zoom-next',
        disabled: true,
        tooltip: "next in history"
    });
    actions["next"] = action;
    toolbarItems.push(action);
    
    toolbarItems.push("->");
    
    // Reuse the GeoExt.Action objects created above
    // as menu items
    //    toolbarItems.push({
    //        text: "menu",
    //        menu: new Ext.menu.Menu({
    //            items: [
    //                // ZoomToMaxExtent
    //                actions["max_extent"],
    //                // Nav
    //                new Ext.menu.CheckItem(actions["nav"]),
    //                // Draw poly
    //                new Ext.menu.CheckItem(actions["draw_poly"]),
    //                // Draw line
    //                new Ext.menu.CheckItem(actions["draw_line"]),
    //                // Select control
    //                new Ext.menu.CheckItem(actions["select"]),
    //                // Navigation history control
    //                actions["previous"],
    //                actions["next"]
    //            ]
    //        })
    //    });
    
    
    action = new GeoExt.Action({
        text: 'Submit Form',
        handler: function(){
            var i, fe;
            var fes = vector.features;
            var impacts = [];
            var results = '';
            for (i = 0; i < fes.length; i++) {
                fe = fes[i];
                if (fe.geometry.CLASS_NAME == "OpenLayers.Geometry.Polygon") {
                    //it is an impact
                    results = results + '\n' + 'polygon: ' + fe.id + '\n' + fe.geometry.toString();
                    
                }
                else 
                    if (fe.geometry.CLASS_NAME == "OpenLayers.Geometry.Point") {
                        //it is an marker
                        results = results + '\n' + 'The center of : ' + fe.attributes.parent + '\n' + fe.geometry.toString();
                    }
                
            }
            
            alert(results)
            
            
        }
        
    })
    toolbarItems.push(action);
    
    
    
    var mapPanel = new GeoExt.MapPanel({
        //        renderTo: "mappanel",
        height: 400,
        width: 600,
		iconCls: 'icon-map',
		title: 'Map Panel',

        map: map,
        center: new OpenLayers.LonLat(-83.019919, 40.001405).transform(new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject()),
        zoom: 15,
        tbar: toolbarItems
    });
    
    
    editform = new EditForm();
    //	editform.hide();
    //north, the header
    var header = new Ext.Panel({
        border: false,
        layout: 'anchor',
        region: 'north',
        cls: 'docs-header',
        height: 30,
        items: [{
            xtype: 'box',
            el: 'header',
            border: false,
            anchor: 'none 0'
        }]
    });//end of header
    //   Define the Grid data and create the Grid
    var myData = [[1, 'project', '02/05/1978', '02/09/2045', 'OSU-12345', 'Mel meng', true, true, true, true, '<h1>header1</h1>'], [2, 'project2', '02/05/1918', '01/09/2045', 'OSU-12345, 2', 'Mel meng ', true, false, false, true, '<h1>header1 2</h1>']];
    
    var ds = new Ext.data.Store({
        reader: new Ext.data.ArrayReader({}, ['projectid', 'project', {
            name: 'start',
            type: 'date',
            dateFormat: 'm/d/Y'
        }, {
            name: 'end',
            type: 'date',
            dateFormat: 'm/d/Y'
        }, 'projectno', 'pm', 'sidewalk', 'roadway', 'garage', 'adaparking', 'description'])
    });
    
    // the DefaultColumnModel expects this blob to define columns. It can be extended to provide
    // custom or reusable ColumnModels
    var cm = new Ext.grid.ColumnModel([{
        id: 'projectid',
        header: "ID",
        width: 160,
        sortable: true,
        locked: false,
        dataIndex: 'projectid'
    },{
        header: "Status",
        width: 55,
        sortable: true,
        dataIndex: 'reviewstatus',
		hidden: true
    }, {
        header: "Start",
        width: 55,
        sortable: true,
        renderer: Ext.util.Format.dateRenderer('m/d/Y'),
        dataIndex: 'start'
    }, {
        header: "End",
        width: 55,
        sortable: true,
        renderer: Ext.util.Format.dateRenderer('m/d/Y'),
        dataIndex: 'end'
    }, {
        header: "Project",
        width: 55,
        sortable: true,
        dataIndex: 'project'
    }, {
        header: "Project#",
        width: 55,
        sortable: true,
        dataIndex: 'projectno'
    }, {
        header: "PM",
        width: 55,
        sortable: true,
        dataIndex: 'pm'
    }, {
        header: "sidewalk",
        width: 65,
        sortable: true,
        dataIndex: 'sidewalk'
    }, {
        header: "roadway",
        width: 65,
        sortable: true,
        dataIndex: 'roadway'
    }, {
        header: "garage",
        width: 65,
        sortable: true,
        dataIndex: 'garage'
    }, {
        header: "adaparking",
        width: 65,
        sortable: true,
        dataIndex: 'adaparking'
    }, {
        header: "description",
        width: 65,
        sortable: true,
        dataIndex: 'description',
        hidden: true
    }]);
    
    
    // create the Data Store
    var store = new Ext.data.JsonStore({
        root: 'results',
//        totalProperty: 'totalCount',
        idProperty: 'projectid',
        remoteSort: true,
        
        fields: [
		'reviewstatus',
		{
            name: 'roadway',
            type: 'boolean'
        }, {
            name: 'description',
            type: 'string'
        }, {
            name: 'end_date',
            type: 'date',
            dateFormat: 'm/d/Y'
        }, {
            name: 'projectno',
            type: 'string'
        }, {
            name: 'projectid',
            type: 'string'
        }, {
            name: 'project',
            type: 'string'
        }, {
            name: 'garage',
            type: 'boolean'
        }, {
            name: 'adaparking',
            type: 'boolean'
        }, {
            name: 'sidewalk',
            type: 'boolean'
        }, {
            name: 'start_date',
            type: 'date',
            dateFormat: 'm/d/Y'
        }, {
            name: 'pm',
            type: 'string'
        }],
        
        // load using script tags for cross domain, if the data in on the same domain as
        // this page, an HttpProxy would be better
        proxy: new Ext.data.HttpProxy({
            url: '/test'
        })
    });
	store.setDefaultSort('start_date', 'desc');

	
	function highlight(val){
		if (val) {
			return '<span style="color:red;">Yes</span>';
		} else {
			return '<span style="color:green;">No</span>';
		}
	};
    gridPanel = new Ext.grid.GridPanel({
        width: 350,
        height: 500,
		iconCls: 'icon-impact',
        
        store: store,
        trackMouseOver: true,
        disableSelection: false,
        loadMask: true,
        
        // grid columns
        columns: [  {
            header: "Project No.",
            dataIndex: 'projectno',
            width: 50,
            sortable: true
        }, {
            header: "ID",
            dataIndex: 'projectid',
            width: 50,
            sortable: true,
			hidden: true
        }, {
            header: "Project",
            dataIndex: 'project',
            width: 100,
            sortable: true
        }
		,{
            header: "PM",
            dataIndex: 'pm',
            width: 50,
            sortable: true
        }, {
            header: "Start",
            dataIndex: 'start_date',
            width: 30,
			renderer: Ext.util.Format.dateRenderer('m/d/Y'),
            sortable: true,
			hidden: true
        }, {
            header: "End",
            dataIndex: 'end_date',
            width: 50,
			renderer: Ext.util.Format.dateRenderer('m/d/Y'),
            sortable: true,
			hidden: true
        },{
            header: "Roadway",
            dataIndex: 'roadway',
            width: 30,
			renderer: highlight,
            sortable: true,
			hidden: true
        }, {
            header: "Garage",
            dataIndex: 'garage',
			renderer: highlight,
            width: 30,
            sortable: true,
			hidden: true
        }, {
            header: "ADA Parking",
            dataIndex: 'adaparking',
			renderer: highlight,
            width: 30,
            sortable: true,
			hidden: true
        }, {
            header: "Sidewalk",
            dataIndex: 'sidewalk',
			renderer: highlight,
            width: 30,
            sortable: true,
			hidden: true
        }],
        sm: new Ext.grid.RowSelectionModel({
            singleSelect: true,
            listeners: {
                rowselect: function(sm, row, rec){
                    //editform.getForm().loadRecord(rec)
					mapPanel.setTitle('Map Panel - ' + rec.data.project)
                }
            }
        }),
		
        // customize view config
        viewConfig: {
            forceFit: true,
            enableRowBody: true,
            showPreview: true,
            getRowClass: function(record, rowIndex, p, store){
                if (this.showPreview) {
					var html = String.format('{0} -- {1}<br>Traffic Impacts:{2}<br>{3}', Ext.util.Format.dateRenderer('m/d/y')(record.data.start_date), Ext.util.Format.dateRenderer('m/d/y')(record.data.end_date), '', record.data.description);
                    p.body = '<p style="color:grey;">' + html + '</p>';
                    return 'x-grid3-row-expanded';
                }
                return 'x-grid3-row-collapsed';
            }
        },
        listeners: {
            //viewready:
            viewready: function(g){
            
                g.getSelectionModel().selectRow(0);
            }
        },
        
        // paging bar on the bottom
        tbar: new Ext.Toolbar({
            items: [{
                xtype: 'button',
                text: 'Delete',
				iconCls: 'icon-delete',
                handler: function(){
                    var sel = gridPanel.getSelectionModel().getSelected();
                    if (sel) {
                        Ext.Ajax.request({
                            url: '/test',
                            params: {
                                projectid: sel.get('projectid'),
                                request_type: 'delete'
                            },
                            method: 'post',
                            success: function(result, request){
                                var jsondata = Ext.util.JSON.decode(result.responseText);
                                if (jsondata.success) {
                                    store.load()
                                    
                                }
                                else {
                                    Ext.Msg.alert('Failed to delete the record')
                                }
                            }
                        })
                    }
                    else {
                        Ext.Msg.alert('No record is selected')
                        
                    }
                }
                
            }, {
                xtype: 'button',
                text: 'Edit',
				iconCls: 'icon-edit',
                handler: function(){
                    var sel = gridPanel.getSelectionModel().getSelected();
                    if (sel) {
                        editform = new EditForm({
                        buttons: [{
                            text: 'Save',
                            handler: function(formpanel, action){
                                editform.getForm().submit({
                                    clientValidation: true,
                                    url: '/test',
                                    method: 'post',
                                    params: {
                                        request_type: 'update'
                                    },
                                    
                                    success: function(form, action){
                                        Ext.Msg.alert('Success', action.result.msg);
										formpanel.findParentByType('window').destroy();
										store.load();
                                    },
                                    failure: function(form, action){
										if (action.failureType=='client'){
											Ext.Msg.alert('Invalid Entry', 'Please fix the errors on your form and try again.')
										} else {
											Ext.Msg.alert('Server error', action.result.msg)
										}
                                        
                                    }
                                });
                            }
                        }, {
                            text: 'Cancel',
							handler: function(form, action){
								form.findParentByType('window').destroy();
							}
                        }]
                    });
						
                        var win = new Ext.Window({
                            title: 'Editing ....',
                            width: 800,
                            height: 600,
                            autoScroll: true,
                            layout: 'fit',
                            items: [editform],
                            modal: true
                        });
                        win.show();
                        editform.getForm().loadRecord(sel)
                    }
                    else {
                        Ext.Msg.alert('No record is selected')
                        
                    }
                    
                }
                
            }, {
                xtype: 'button',
                text: 'New',
				iconCls: 'icon-add',
                handler: function(){
                    
					editform = new EditForm({
                        buttons: [{
                            text: 'Save',
                            handler: function(formpanel, action){
                                editform.getForm().submit({
                                    clientValidation: true,
                                    url: '/test',
                                    method: 'post',
                                    params: {
                                        request_type: 'new'
                                    },
                                    
                                    success: function(form, action){
                                        Ext.Msg.alert('Success', action.result.msg);
										formpanel.findParentByType('window').destroy();
										store.load();
                                    },
                                    failure: function(form, action){
										if (action.failureType=='client'){
											Ext.Msg.alert('Invalid Entry', 'Please fix the errors on your form and try again.')
										} else {
											Ext.Msg.alert('Server error', action.result.msg)
										}
                                        
                                    }
                                });
                            }
                        }, {
                            text: 'Cancel',
							handler: function(form, action){
								form.findParentByType('window').destroy();
							}
                        }]
                    });
					
					win = new Ext.Window({
                        title: 'New Impact ....',
                        width: 800,
                        height: 600,
                        autoScroll: true,
                        layout: 'fit',
                        items: [editform],
                        modal: true
                    });
                    
                    win.show();
                    
                    
                }
                
            }, {
                xtype: 'button',
                pressed: true,
                enableToggle: true,
                text: 'Show Preview',
//                cls: 'x-btn-text-icon details',
                toggleHandler: function(btn, pressed){
                    var view = gridPanel.getView();
                    view.showPreview = pressed;
                    view.refresh();
                }
            }]
        })
    });

    var viewport = new Ext.Viewport({
        layout: 'border',
		frame: true,
        items: [header, {
            region: 'south',
            border: true,
            html: '<div style="text-align: center;font-size: 80%;color:black;">OSU Constructin Impact Editor - by Mel Meng May 2009, <a href="http://www.dlz.com">DLZ</a>. ymeng@dlz.com<div>'
        
        }

		, {
            region: 'west',
			collapsible: true,
            layout: 'fit',
            border: false,
            collapsible: true,
			title: 'Impact List',
			iconCls: 'icon-impact',
            id: 'img-detail-panel',
            split: true,
            width: 350,
            items: [gridPanel]
        },{
			region: 'center',
			layout: 'fit',
			items: mapPanel
		}]
    });//end of viewport
    store.load();
	loginwin.show()
    
    
});
